<template>
  <div class="dict-management">
    <!-- 标题 -->
    <h2 class="title">数据字典管理</h2>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <span class="filter-label">模糊匹配：</span>
      <el-input v-model="searchValue" placeholder="模糊查询" class="filter-input" clearable></el-input>
      <span class="filter-label">所属模块：</span>
        <DropdownDictSelect v-model="searchModule" dictName="ALL_MODULE" :spaceId="0" />
      <div class="actions">
        <el-button type="primary">导出 JSON</el-button>
        <el-button type="success" @click="toggleDrawer('create')">创建新字典</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table :data="dictData" border style="width: 100%; margin-top: 20px">
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column label="字典名称" prop="dictName">
        <template #default="scope">
          <a @click="goToDetail(scope.row.id.toString())">{{ scope.row.dictName }}</a>
        </template>
      </el-table-column>
      <el-table-column label="字典中文名称" prop="dictNameCn" width="120"></el-table-column>
      <el-table-column label="所属模块" prop="module"></el-table-column>
      <el-table-column label="字典创建人" prop="createBy" width="100">
        <template #default="scope">
          {{ scope.row.createBy || "无" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" prop="updateTime">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="是否生效" width="100" >
        <template #default="scope">
          <el-button
              size="mini"
              :style="{ backgroundColor: scope.row.isActive == 1 ? 'green' : 'red', color: 'white' }"
              :disabled="true"
          >
            {{ scope.row.isActive == 1 ? "生效" : "失效" }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-link type="primary" @click="toggleDrawer('update', scope.row)">修改</el-link>
          <span class="link-spacing"></span>
          <el-link type="danger" @click="confirmDelete(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:currentPage="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper, ->, total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; text-align: right;"
    ></el-pagination>


    <!-- 添加 DictDrawer 组件 -->
    <DictDrawer
        v-model="drawerVisible"
        :operation="currentOperation"
        :dict-id="currentDictId"
        @close="closeDrawer"
        @save="loadDictData"
    />
  </div>
</template>

<script>
import { ref, watch } from 'vue';
import { debounce } from 'lodash';
import { queryPageDicts, createDict, updateDict, deleteDict, getDictDetails } from '@/service/admin/admin.service';
import { ElMessageBox, ElMessage } from 'element-plus';
import DictDrawer from '@/views/Admin/Drawer/DictDrawer.vue';
import { useRouter } from 'vue-router';
import DropdownDictSelect from "@/components/dropdown/DropdownSelect.vue";

export default {
  components: {DropdownDictSelect, DictDrawer },
  setup() {
    const searchValue = ref('');
    const currentOperation = ref('create');
    const currentDictId = ref(null);
    const searchModule = ref('');
    const dictData = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const drawerVisible = ref(false);
    const router = useRouter();

    // 切换 Drawer 显示/隐藏
    const toggleDrawer = (operation, row = null) => {
      console.log("当前的抽屉状态：{}",drawerVisible.value)
      currentOperation.value = operation;
      currentDictId.value = row ? row.id : null;
      drawerVisible.value = !drawerVisible.value;
      console.log("切换后的抽屉状态：{}",drawerVisible.value)
    };

    const closeDrawer = () => {
      drawerVisible.value = false;
    };

    const goToDetail = (id) => {
      router.push(`/admin/dictionary/${id}`);
    };

    const confirmDelete = (dictId) => {
      ElMessageBox.confirm('是否确认删除该字典？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            deleteDict( dictId , (response) => {
              if (response.status === 'success') {
                ElMessage.success('字典删除成功');
                loadDictData();
              }
            });
          })
          .catch(() => {
            console.log('删除操作取消');
          });
    };

    const loadDictData = async () => {
      const params = {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        searchValue: searchValue.value,
        searchModule: searchModule.value
      };
      queryPageDicts(params, (response) => {
        if (response.status === 'success') {
          dictData.value = response.data.records;
          total.value = response.data.total;
        }
      });
    };

    const debouncedLoadDictData = debounce(loadDictData, 500);

    watch([searchValue, searchModule], () => {
      debouncedLoadDictData();
    });

    const formatDate = (dateString) => {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = date.getMinutes();
      return `${year}年${month}月${day}日${hours}时${minutes}分`;
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      loadDictData();
    };
    const handleSizeChange = (size) => {
      pageSize.value = size;
      loadDictData();
    };

    loadDictData();

    return {
      searchValue,
      searchModule,
      dictData,
      currentPage,
      pageSize,
      total,
      drawerVisible,
      currentOperation,
      currentDictId,
      toggleDrawer,
      closeDrawer,
      goToDetail,
      confirmDelete,
      loadDictData,
      formatDate,
      handlePageChange,handleSizeChange
    };
  }
};
</script>

<style scoped>
.dict-management {
  padding: 20px;
}

.title {
  padding-bottom: 5px;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 10px;
  padding-bottom: 10px;
}

.filter-label {
  font-size: 14px;
  margin-right: 5px;
}

.filter-input,
.filter-select {
  width: 200px;
}

.actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.link-spacing {
  display: inline-block;
  width: 10px;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.drawer-footer .el-button {
  margin-left: 10px;
}
</style>
